package com.szewec.ps.ui.appauth;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.BaseUrl;
import com.szewec.ps.base.ListBaseAdapter;
import com.szewec.ps.base.SuperViewHolder;
import com.szewec.ps.databinding.ActivityAppAuthBinding;
import com.szewec.ps.model.project.SelectUserModel;
import com.szewec.ps.util.LogUtil;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.SharedPreferencesUtil;
import com.szewec.ps.util.dialog.LoadingDialog;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class AppAuthActivity extends BaseActivity {
    private static final String TAG = "AppAuthActivity";
    private ActivityAppAuthBinding binding;
    //选项卡flag
    private boolean isAuth = true;

    /**
     * recycleView相关
     */
    private DataAdapter authDataAdapter;
    private LRecyclerViewAdapter authLRecyclerViewAdapter;
    private List<SelectUserModel> authUserList = new ArrayList<>();
    private DataAdapter unauthDataAdapter;
    private LRecyclerViewAdapter unauthLRecyclerViewAdapter;
    private List<SelectUserModel> unauthUserList = new ArrayList<>();

    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_auth);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_app_auth);
        ButterKnife.bind(this);
        loadingDialog = LoadingDialog.getInstance(this);


        initTitleBar();
        //初始化数据
        initData();
        //初始化view
        initRecycleView();
    }

    private void initTitleBar(){
        binding.titleBar.setLeftLayoutVisibility(View.VISIBLE);
        binding.titleBar.setLeftLayoutClickListener(this::finish);
        binding.titleBar.setRightLayoutVisibility(View.VISIBLE);
        binding.titleBar.setRightTextVisibility(View.VISIBLE);
        binding.titleBar.setRightText("取消授权");
    }

    private void initRecycleView(){
        //已授权
        authDataAdapter = new DataAdapter(this);
        authLRecyclerViewAdapter = new LRecyclerViewAdapter(authDataAdapter);
        binding.lrvAuth.setAdapter(authLRecyclerViewAdapter);

        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(this);
        binding.lrvAuth.setLayoutManager(linearLayoutManager1);
        binding.lrvAuth.setPullRefreshEnabled(false);
        binding.lrvAuth.setLoadMoreEnabled(false);
        //未授权
        unauthDataAdapter = new DataAdapter(this);
        unauthLRecyclerViewAdapter = new LRecyclerViewAdapter(unauthDataAdapter);
        binding.lrvUnauth.setAdapter(unauthLRecyclerViewAdapter);
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(this);
        binding.lrvUnauth.setLayoutManager(linearLayoutManager2);
        binding.lrvUnauth.setPullRefreshEnabled(false);
        binding.lrvUnauth.setLoadMoreEnabled(false);
    }


    private void initData(){
        String companyId = (String) SharedPreferencesUtil.getData(PreferincesContext.COMPANY_ID,"");
        HashMap<String,Object> params = new HashMap<>();
        params.put("companyId",companyId);
        params.put("appId", BaseUrl.APP_ID);
        OkHttp.get("/tpms-plan-service/api/roles-management/get-user-by-companyId", params, loadingDialog, new OkHttp.MyCallback() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i(TAG,result);
                JSONObject data = JSONObject.parseObject(result).getJSONObject("data");
                JSONArray authorizedUsers = data.getJSONArray("authorizedUsers");
                JSONArray unauthorizedUsers = data.getJSONArray("unauthorizedUsers");
                authUserList = authorizedUsers.toJavaList(SelectUserModel.class);
                unauthUserList = unauthorizedUsers.toJavaList(SelectUserModel.class);
                refreshUI();
            }
        });
    }

    private void refreshUI(){
        runOnUiThread(()->{
            authDataAdapter.setDataList(authUserList);
            authDataAdapter.notifyDataSetChanged();
            unauthDataAdapter.setDataList(unauthUserList);
            unauthDataAdapter.notifyDataSetChanged();
            loadingDialog.close();
        });
    }

    @OnClick({R.id.cl_auth,R.id.cl_unauth,R.id.right_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cl_auth:
                //已授权
                if (isAuth){
                    return;
                }else {
                    isAuth = true;
                    updateTabUI();
                }
                break;
            case R.id.cl_unauth:
                //未授权
                if (!isAuth){
                    return;
                }else {
                    isAuth = false;
                    updateTabUI();
                }
                break;
            case R.id.right_layout:
                //保存逻辑
                LogUtil.i(TAG,"当前选项卡是已授权:"+ isAuth);
                doSave();
                break;
        }
    }

    private void doSave(){
        StringBuilder sb = new StringBuilder();
        if (isAuth){
            for(int i=0;i<authUserList.size();i++){
                if (authUserList.get(i).getIfSelected()){
                    sb.append(authUserList.get(i).getUserId());
                    if (i != authUserList.size() - 1){
                        sb.append(",");
                    }
                }
            }
        }else {
            for(int i=0;i<unauthUserList.size();i++){
                if (unauthUserList.get(i).getIfSelected()){
                    sb.append(unauthUserList.get(i).getUserId());
                    if (i != unauthUserList.size() - 1){
                        sb.append(",");
                    }
                }
            }
        }
        String tenantId = (String)SharedPreferencesUtil.getData(PreferincesContext.COMPANY_ID,"");
        AuthModel authModel = new AuthModel(BaseUrl.APP_ID,tenantId,!isAuth,sb.toString());
        OkHttp.post("/tpms-plan-service/api/roles-management/auth", authModel, new OkHttp.MyCallback() {
            @Override
            public void onSuccess(String result) {
                LogUtil.i(TAG,"授权或取消授权成功");
                initData();
            }
        });
    }

    private void updateTabUI(){
        if (isAuth){
            binding.titleBar.setRightText("取消授权");
            binding.vAuth.setVisibility(View.VISIBLE);
            binding.vUnauth.setVisibility(View.GONE);
            binding.tvAuth.setTextColor(getResources().getColor(R.color.C2A84FC));
            binding.tvUnauth.setTextColor(getResources().getColor(R.color.C333333));
            binding.lrvAuth.setVisibility(View.VISIBLE);
            binding.lrvUnauth.setVisibility(View.GONE);
        }else {
            binding.titleBar.setRightText("授权");
            binding.vAuth.setVisibility(View.GONE);
            binding.vUnauth.setVisibility(View.VISIBLE);
            binding.tvUnauth.setTextColor(getResources().getColor(R.color.C2A84FC));
            binding.tvAuth.setTextColor(getResources().getColor(R.color.C333333));
            binding.lrvAuth.setVisibility(View.GONE);
            binding.lrvUnauth.setVisibility(View.VISIBLE);
        }
    }

    private class DataAdapter extends ListBaseAdapter<SelectUserModel> {


        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_multi_check;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView name = holder.getView(R.id.member_Name);
            TextView phone = holder.getView(R.id.member_Phone);
            ImageView checked = holder.getView(R.id.ic_select);
            SelectUserModel model = mDataList.get(position);
            name.setText(model.getName());
            phone.setText(model.getPhoneNumber());
            if (model.getIfSelected()){
                checked.setVisibility(View.VISIBLE);
            }else {
                checked.setVisibility(View.GONE);
            }
            //行点击监听事件
            holder.itemView.setOnClickListener(view -> {
                if (model.getIfSelected()){
                    model.setIfSelected(false);
                    checked.setVisibility(View.GONE);
                }else {
                    model.setIfSelected(true);
                    checked.setVisibility(View.VISIBLE);
                }
            });
        }
    }
}
